<?php

namespace App\Http\Controllers\Admin\Warehouse;

use App\Exceptions\AppException;
use App\Http\Controllers\Controller;
use App\Models\AdminModel;
use App\Models\cainiao\NotifyModel;
use App\Models\CountryModel;
use App\Models\customer\OrderRuleModel;
use App\Models\dispatch\PlaceModel;
use App\Models\lazada\BigBagModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

//入库
class Storage extends Controller
{

    /**
     * Notes:验证大包号
     * User: xiangzi
     * Date: 2024/10/26
     * Time: 下午2:45
     * @return \Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        $customer_id = $request->input('customer_id', 0);
        $destination = $request->input('destination', 0);
        $goods_attr = $request->input('goods_attr', 0);
        $bigBagID = $request->input('bigBagID', '');

        if(!$customer_id){
            return $this->error('请选择大客户');
        }

//        if(!$goods_attr){
//            return $this->error('请选择货物属性');
//        }

        if(!$bigBagID){
            return $this->error('大包号不能为空');
        }

        $find = BigBagModel::where('bigBagID', $bigBagID)->first();

        if($find){
            if($find->customer_id != $customer_id){
                return $this->success(['result' => 0, 'msg' => '平台不一致']);
            }

            if($destination && $find->destination != $destination){
                return $this->success(['result' => 0, 'msg' => '目的地不一致']);
            }

//            $des_country_name = CountryModel::where('id', $des_country_id)->value('name');

            if($goods_attr && $find->cargoType != $goods_attr){
                return $this->success(['result' => 0, 'msg' => '货物属性不一致']);
            }

            if($find->order_id){
                return $this->error('该大包号已入库');
            }
            return $this->success([
                'id' => $find->id,
                'customer_name' => 'lazada',
                'bigBagID' => $find->bigBagID,
                'des_country_name' => $destination,
                'goods_attr' => $find->cargoType == 2 ? '敏货' : '普货',
            ]);
        }else{
//            $model = new NotifyModel();
//            $model->bigBagID = $bigBagID;
//            $model->customer_id = $customer_id;
//            $model->des_country_id = $des_country_id;
//            $model->cargoType = $goods_attr;
//            $model->is_lack = 1;
//            $model->save();

            return $this->error('该大包号不存在');
        }
    }


    /**
     * Notes:批量验证大包号
     * User: xiangzi
     * Date: 2024/10/26
     * Time: 下午2:45
     * @return \Illuminate\Http\JsonResponse
     */
    public function check_batch(Request $request)
    {
        $customer_id = $request->input('customer_id', 0);
        $destination = $request->input('destination', 0);
        $goods_attr = $request->input('goods_attr', 0);
        $bigBagIDs = $request->input('bigBagID', []);

        if(!$customer_id){
            return $this->error('请选择大客户');
        }

        if(!$bigBagIDs){
            return $this->error('大包号不能为空');
        }

        $find = BigBagModel::whereIn('bigBagID', $bigBagIDs)->where('order_id', 0)->get();

        if(!$find){
            return $this->error('请输入正确的大包号');
        }

        if(count($find) != count($bigBagIDs)){
            $find_bigBagIDs = $find->pluck('bigBagID')->toArray();
            $error_bigBagIDs = array_diff($bigBagIDs, $find_bigBagIDs);
            return $this->error('大包号不存在或已入库：'.implode(',', $error_bigBagIDs));
        }

        if($find){
            $find_customer_id = $find->pluck('customer_id')->toArray();
            $find_customer_id = array_unique($find_customer_id);
            if(count($find_customer_id) != 1 && $find_customer_id[0] != $customer_id){
                return $this->error('平台不一致');
            }

            $find_destination = $find->pluck('destination')->toArray();
            $find_destination = array_unique($find_destination);
            if(count($find_destination) != 1 && ($destination && $find_destination[0] != $destination)){
                return $this->error('目的地不一致');
            }

            $find_goods_attr = $find->pluck('cargoType')->toArray();
            $find_goods_attr = array_unique($find_goods_attr);
            if(count($find_goods_attr) != 1 && ($goods_attr && $find_goods_attr[0] != $goods_attr)){
                return $this->error('货物属性不一致');
            }

            $return = [];

            foreach ($find as $value){
                $return[] = [
                    'id' => $value->id,
                    'customer_name' => 'lazada',
                    'bigBagID' => $value->bigBagID,
                    'des_country_name' => $value->destination,
                    'goods_attr' => $value->cargoType == 2 ? '敏货' : '普货',
                ];
            }

            return $this->success($return);
        }else{
            return $this->error('大包号不存在');
        }
    }


    /**
     * Notes:平台货入库
     * User: xiangzi
     * Date: 2024/10/26
     * Time: 下午4:02
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request) {
        $auth = $request->get('auth');
        $params = $request->all();

        $validator = Validator::make($params, [
            'customer_id' => 'required',
            'goods_label' => 'required',
            'place_id' => 'required|integer',
            'ids' => 'required|array'
        ], [
            'customer_id.required' => '请选择平台',
            'goods_label.required' => '请填写货物标签',
            'place_id.required' => '请选择库位',
            'ids.required' => '大包号不能为空',
            'ids.array' => '大包号必须为数组'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $destination = 0;
        foreach ($params['ids'] as $id){
            $destination_find = BigBagModel::where('id', $id)->value('destination');
            if($destination_find){
                $destination = $destination_find;
                break;
            }
        }

        $find_place = PlaceModel::find($params['place_id']);

        if(!$find_place){
            return $this->error('请选择库位');
        }

        $warehouse_id = $find_place->warehouse_id;

        DB::beginTransaction();
        try{
            $model = new OrderModel();
            $model->sn = $this->get_order_sn($params['customer_id']);
            $model->customer_id = $params['customer_id'];
            $model->goods_label = $params['goods_label'];
            $model->place_id = $params['place_id'];
            $model->status = OrderModel::STATUS_STORAGE;
            $model->storage_remark = $params['storage_remark'] ?? '';
            $model->storage_time = date('Y-m-d H:i:s');
            $model->big_pkgs = count($params['ids']) ?? 0;
            $model->is_platform = 1;
            $model->destination = $destination;
            $model->save();

            $small_pkgs = 0; $storage_weight = 0;
            foreach ($params['ids'] as $id){
                $find = BigBagModel::where('id', $id)->first();
                if($find){
                    $find->order_id = $model->id;
                    $find->place_id = $params['place_id'];
                    $find->warehouse_id = $warehouse_id;
                    $find->save();

                    $small_pkgs += $find->parcelQty;
                    $storage_weight += round($find->bigBagWeight / 1000, 2);
                }
//                else{
//                    $model_notify = new BigBagModel();
//                    $model_notify->bigBagID = $bigBagID;
//                    $model_notify->customer_id = $params['customer_id'];
//                    $model_notify->order_id = $model->id;
//                    $model_notify->save();
//                }
            }

            $model->small_pkgs = $small_pkgs;
            $model->storage_weight = $storage_weight;
            $model->save();


            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();

    }


    public function get_order_sn($customer_id) {
        $rule = OrderRuleModel::where('customer_id', $customer_id)->first();
        if($rule){
            $prefix = $rule->prefix;
            $suffix = $rule->suffix;

            return $prefix . $suffix . date('Ymd') . get_big_order_sn($rule->serial_number);
        }else{
            return '';
        }


    }


}
